package com.example.demo.service;

import com.example.demo.common.domain.User;
import com.example.demo.common.domain.UserExample;
import com.example.demo.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.Collection;
import java.util.List;

@Service
public class UserMgService {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private UserExample userExample;

    public User queryUser(String uname){
        return  userMapper.selectByPrimaryKey(uname);
    }
    public List<User> queryAllUser(){
        userExample.createCriteria();
        List<User> userList=userMapper.selectByExample(userExample);
        userExample.clear();
        return  userList;
    }
    public List<User> queryUserByNP(User user) {
        String Uname=user.getuName();
        String phone=user.getPhone();
        Boolean falgU=!(Uname.isEmpty()||Uname==null||Uname.equals("请输入你需要查询的用户名"));
        Boolean falgP=!(phone.isEmpty()||phone==null||phone.equals("请输入你需要查询的手机号"));
        System.out.println("D:"+falgU+",K:"+falgP);
        if (falgU&&falgP){  userExample.createCriteria().andUNameLike("%"+Uname+"%").andPhoneLike("%"+phone+"%");}
        if(falgU==true&&falgP==false){ userExample.createCriteria().andUNameLike("%"+Uname+"%");}
        if(falgU==false&&falgP==true){userExample.createCriteria().andPhoneLike("%"+phone+"%");}
        if(falgU==false&&falgP==false){userExample.createCriteria();}

       List<User> userList= userMapper.selectByExample(userExample);
        userExample.clear();
        return  userList;
    }
    public String deleteByUnames(String[] uNamelist ){
        List<String> collection = Arrays.asList(uNamelist);
        userExample.createCriteria().andUNameIn(collection);
       userMapper.deleteByExample(userExample);
       userExample.clear();
        return  "删除完成";
    }

    public String AddUser(User user){

        Boolean flag;
        String message="";
        String Uname= user.getuName();
        System.out.println("执行一次查询：");
        User user1=userMapper.selectByPrimaryKey(Uname);
        if (user1==null){
            message="正确";
            flag=true;
        } else {
            message="账户已存在，请重新添加";
            flag=false;
        }
        if (flag){
            userMapper.insertSelective(user);
        }
        return message;
    }

   public String UpdateRole(User user){
        String message="";
       System.out.println("用户的权限："+user.getRole());
        if (user.getRole()>1) {
            userMapper.updateByPrimaryKeySelective(user);
            message="更新成功";
        }else {message="你的权限不够";}

        return  message;
   }
    public String deleteByuser(String Uname){
        userMapper.deleteByPrimaryKey(Uname);
        return "删除完成";
    }
}
